import { useUserStore } from '@/store/modules/user'
import logger from '@/utils/logger'
import { createRouter, createWebHistory } from 'vue-router'
import { HOME_ROUTE_PATH, LOGIN_ROUTE_NAME, staticRoutes } from '@/router/static'
import type { App } from 'vue'
import NProgress from '@/plugins/nprogress'
import { addRoutes, buildRoutes } from '@/utils/router'
import { getMenuListApi } from '@/api/login/admin'
import { useMenuStore } from '@/store/modules/menu'

const router = createRouter({
  strict: true,
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoutes
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  //统一设置日志命名空间为当前页面name值
  logger.setNamespace(to.name == undefined ? '' : to.name.toString())
  // logger.info("当前 to：", to, "当前 from:", from)
  const userStore = useUserStore()
  //当前路由是否需要登录
  const isNeedLogin = to.meta.isNeedLogin == undefined || to.meta.isNeedLogin
  //默认所有均需要登录
  if (isNeedLogin && !userStore.isLoggedIn) {
    logger.info("未登录跳转到登录页")
    //跳转到登录页
    next({
      name: LOGIN_ROUTE_NAME,
      query: { redirect: to.fullPath }
    })
    return;
  }
  //如果是登录页，已登录则跳转至redirect
  if (to.name == LOGIN_ROUTE_NAME && userStore.isLoggedIn) {
    const toPath = (to.query.redirect ? to.query.redirect : HOME_ROUTE_PATH) as string;
    logger.info("已登录从登录页跳回之前的页面", toPath)
    next(toPath)
    return;
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})

const addDynamicRoutes = async () => {
  const modules = import.meta.glob('@/views/**/*.vue');
  getMenuListApi().then(res => {
    //构建树形路由
    const routes = buildRoutes(res, modules)
    const menuStore = useMenuStore()
    //更新仓库路由
    menuStore.setRoutes(routes)
    //注册路由
    addRoutes(routes)
  })
}

export const setupRouter = async (app: App<Element>) => {
  logger.info("------------------注册动态路由 start------------------")
  await addDynamicRoutes()
  logger.info("------------------注册动态路由 end------------------")
  app.use(router)
  logger.info("------------------挂载路由完毕------------------")
}

export default router
